package com.cskaoyan.config;

import com.cskaoyan.shiro.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

// 认证器 通过token 进行认证内容分发
public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();
        Collection<Realm> originRealms = getRealms();

        MallToken mallToken = (MallToken) authenticationToken;
        String type = mallToken.getType();

        ArrayList<Realm> realms = new ArrayList<>();
        for (Realm originRealm : originRealms) {
            // 后台adminRealm  前台wxRealm
            if (originRealm.getName().toLowerCase().contains(type)){
                realms.add(originRealm);
            }
        }

        if (realms.size() == 1) {
            return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
        } else {
            return doMultiRealmAuthentication(realms, authenticationToken);
        }
        //return super.doAuthenticate(authenticationToken);
    }
}
